package servlet.zyb;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class LookVoteServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {
			process(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException, Exception {

		req.setCharacterEncoding("UTF-8");
		String qName = (String) req.getSession().getAttribute("qName");
		SAXBuilder builder = new SAXBuilder();

		Document document = builder.build(new File(
				"E:\\MyeclipseWorkspace\\vote\\question.xml"));
		Element root = document.getRootElement();
		System.out.println(root.getName());
		List<Element> list = root.getChildren();
		Map<String, Integer> map = new HashMap<String, Integer>();
		int count = 0;
		for (int i = 0; i < list.size(); i++) {
			Element question = list.get(i);
			Element questionname = question.getChild("questionname");

			if (questionname.getText().equals(qName)) {

				Element options = question.getChild("options");
				List<Element> option = options.getChildren();
				Element users = question.getChild("users");
				List<Element> user = users.getChildren();
				System.out.println("users:" + user.size());
				req.setAttribute("people", user.size());

				for (int j = 0; j < option.size(); j++) {

					String key = option.get(j).getText();
					System.out.println("key:" + key);

					for (int k = 0; k < user.size(); k++) {
						String userContent = user.get(k).getText();
						System.out.println("userContent:" + userContent);
						if (key.equals(userContent)) {
							if (map.get(key) == null) {
								map.put(key, 1);
							} else {
								int num = map.get(key);
								map.put(key, num + 1);
							}
						}
					}
				}
			}
		}
		req.setAttribute("map", map);

		req.getRequestDispatcher("showVoteResult.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			process(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
